/**
 * 图片延迟加载：浏览器加载线程有限
 * 
 * 
 */
/**
 * 解决返回顶部的scroll多次触动的问题
 */
var throttle = function() {
    var isClear = arguments[0], fn;
    // 如果第一个参数是boolean类型那么第一个参数表示是否清楚计时器
    if (typeof isClear === 'boolean') {
        fn = arguments[1];
        fn.__throttleID && clearTimeout(fn.__throttleID);
    } else {
        fn = isClear;
        param = arguments[1];
        var p = extend({
            context: null,//函数执行作用域
            args: [],//函数执行相关参数
            time: 300//函数执行延迟时间
        }, param);
        arguments.callee(true, fn);
        fn.__throttleID = setTimeout(function() {
            fn.apply(p.context, p.args);
        }, p.time);
    }
}

 /**
  * 节流延迟加载图片类
  */
function LazyLoad(id) {
    this.container = document.getElementById(id);
    this.imgs = this.getImgs();
    this.init();
}

LazyLoad.prototype = {
    // 起始执行逻辑
    init: function() {
        this.update();
        this.bindEvent();
    },
    // 获取延迟加载图片
    getImgs: function() {
        var arr = [];
        var imgs = this.container.getElementsByTagName('img');
        for(var i = 0, len = imgs.length; i < len; i++) {
            arr.push(imgs[i]);
        }
        return arr;
    },
    // 加载图片,遍历每一个图片元素，如果处在可视区域内则加载并将其在图片缓存中清除
    update: function() {
        //如果图片都加载完成，返回
        if (!this.imgs.length) {
            return;
        }
        var i = this.imgs.length;
        for (--i; i >= 0; i--) {
            if (this.shouldShow(i)) {
                this.imgs[i].src = this.imgs[i].getAttribute('data-src');
                this.imgs.splice(i, 1);
            }
        }
    },
    // 判断图片是否在可视范围内
    shouldShow: function(i) {
        var img = this.imgs[i],
            scrollTop = document.documentElement.scrollTop || document.body.scrollTop,
            scrollBottom = scrollTop + document.documentElement.clientHeight,
            imgTop = this.pageY(img),
            imgBottom = imgTop + img.offsetHeight;
            if (imgBottom > scrollTop && imgBottom < scrollBottom || (imgTop > scrollTop && imgTop < scrollBottom ))
                return true;
            return false;
    },
    // 获取元素页面中的纵坐标位置
    pageY: function(element) {
        if (element.offsetParent) {
            return element.offsetTop + this.pageY(element.offsetParent);
        } else {
            return element.offsetTop;
        }
    },
    // 绑定事件
    on: function(element, type, fn) {
        if (element.addEventListener) {
            addEventListener(type, fn, false);
        } else {
            element.attachEvent('on' + type, fn, false);
        }
    },
    // 为窗口绑定resize事件与scroll事件
    bindEvent: function() {
        var that = this;
        this.on(window, 'resize', function() {
            throttle(that.update, {context: that});
        });
        this.on(window, 'scroll', function() {
            throttle(that.update, {context: that});
        });
    }
};

new LazyLoad('container');
